package com.example.wxy.bbtapp.DeviceService;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by songxiaolin on 2017/9/17.
 */

public class CommandHelper {
    public static String execCommand(String... command) {
        Process process = null;
        InputStream errIs = null;
        InputStream inIs = null;
        String result = "";

        try {
            process = new ProcessBuilder().command(command).start();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int read = -1;
            errIs = process.getErrorStream();
            while ((read = errIs.read()) != -1) {
                baos.write(read);
            }
            inIs = process.getInputStream();
            while ((read = inIs.read()) != -1) {
                baos.write(read);
            }
            result = new String(baos.toByteArray());
            if (inIs != null)
                inIs.close();
            if (errIs != null)
                errIs.close();
            process.destroy();
        } catch (IOException e) {
            result = e.getMessage();
        }
        return result;
    }


    public void sendTest(String command){
        if (command == null) {
            return;
        }
        try {
            Process process = null;
            DataOutputStream os = null;
            if(null==process){
//              process = Runtime.getRuntime().exec("sh");//系统签名，push到app目录下用这个这个
                process = Runtime.getRuntime().exec("su");//有root权限的用这个;
                os = new DataOutputStream(process.getOutputStream());
            }
            os.write(command.getBytes());
            os.writeBytes("\n");
            os.flush();
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}
